package org.jeecg.modules.farming.news.controller;

import java.sql.Wrapper;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.chuanglan.ChuangLanSmsHelper;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.farming.news.entity.News;
import org.jeecg.modules.farming.news.entity.NewsComment;
import org.jeecg.modules.farming.news.entity.NewsPraise;
import org.jeecg.modules.farming.news.service.INewsPraiseService;
import org.jeecg.modules.farming.news.service.INewsService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.farming.product.entity.FaProduct;
import org.jeecg.modules.system.entity.SysAnnouncement;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.SecurityUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 新闻咨询
 * @Author: jeecg-boot
 * @Date:   2020-12-11
 * @Version: V1.0
 */
@Api(tags="新闻咨询")
@RestController
@RequestMapping("/news/news")
@Slf4j
public class NewsController extends JeecgController<News, INewsService> {
	 @Autowired
	 private INewsService newsService;
	 @Autowired
	 private INewsPraiseService praiseService;
	 @Autowired
	 private ISysUserService sysUserService;
	 @Value("${wx.fullUrl}")
	 private String fullUrl;
	/**
	 * 分页列表查询
	 *
	 * @param news
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "新闻咨询-分页列表查询")
	@ApiOperation(value="新闻咨询-分页列表查询", notes="新闻咨询-分页列表查询")
	@GetMapping(value = "/list")
	@PermissionData(pageComponent="news/NewsList")
	public Result<?> queryPageList(News news,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<News> queryWrapper = QueryGenerator.initQueryWrapper(news, req.getParameterMap());
		Page<News> page = new Page<News>(pageNo, pageSize);
		IPage<News> pageList = newsService.page(page, queryWrapper);
		List<News> records = pageList.getRecords();
		if(records !=null && records.size()>0){
			for(int i =0;i<records.size();i++){
				News n = records.get(i);
				if(n.getAttachment() != null)
				{
					String[] split = n.getAttachment().split(",");
					String strUrl = "";
					for(int j=0;j<split.length;j++)
					{
						String url = split[j];
						strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
					}
					if(strUrl.length()>1)
					{
						strUrl = strUrl.substring(0,strUrl.length() - 1);
					}
					records.get(i).setAttachment(strUrl);
				}
				if(n.getImgUrl() !=null){
					String[] split = n.getImgUrl().split(",");
					String strUrl = "";
					for(int j=0;j<split.length;j++)
					{
						String url = split[j];
						strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
					}
					if(strUrl.length()>1)
					{
						strUrl = strUrl.substring(0,strUrl.length() - 1);
					}
					records.get(i).setImgUrl(strUrl);
				}
			}
			pageList.setRecords(records);
		}
		return Result.OK(pageList);
	}
	 /**
	  * 分页列表查询
	  *
	  * @param news
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "新闻咨询-分页列表查询")
	 @ApiOperation(value="新闻咨询-分页列表查询", notes="新闻咨询-分页列表查询")
	 @GetMapping(value = "/min/list")
	 public Result<?> queryPageMinList(News news,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<News> queryWrapper = QueryGenerator.initQueryWrapper(news, req.getParameterMap());
		 queryWrapper.orderByDesc("create_time");
		 Page<News> page = new Page<News>(pageNo, pageSize);
		 IPage<News> pageList = newsService.page(page, queryWrapper);
		 List<News> records = pageList.getRecords();
		 if(records !=null && records.size()>0){
			 for(int i =0;i<records.size();i++){
				 News n = records.get(i);
				 if(n.getAttachment() != null)
				 {
					 String[] split = n.getAttachment().split(",");
					 String strUrl = "";
					 for(int j=0;j<split.length;j++)
					 {
						 String url = split[j];
						 strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
					 }
					 if(strUrl.length()>1)
					 {
						 strUrl = strUrl.substring(0,strUrl.length() - 1);
					 }
					 records.get(i).setAttachment(strUrl);
				 }
				 if(n.getImgUrl() !=null){
					 String[] split = n.getImgUrl().split(",");
					 String strUrl = "";
					 for(int j=0;j<split.length;j++)
					 {
						 String url = split[j];
						 strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
					 }
					 if(strUrl.length()>1)
					 {
						 strUrl = strUrl.substring(0,strUrl.length() - 1);
					 }
					 records.get(i).setImgUrl(strUrl);
				 }
			 }
			 pageList.setRecords(records);
		 }
		 return Result.OK(pageList);
	 }
	/**
	 *   添加
	 *
	 * @param news
	 * @return
	 */
	@AutoLog(value = "新闻咨询-添加")
	@ApiOperation(value="新闻咨询-添加", notes="新闻咨询-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody News news) {
		LoginUser sysLoginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		news.setUnionId(sysLoginUser.getId());
		SysUser sysuser = sysUserService.getById(sysLoginUser.getId());
		news.setAuthor(sysuser.getUnionName());
		news.setPraiseCount(0);
		news.setClickCount(0);
		news.setUnionName(sysuser.getUnionName());
		news.setIsPraise(0);
		news.setStatus(1);  //审核中
		newsService.save(news);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param news
	 * @return
	 */
	@AutoLog(value = "新闻咨询-编辑")
	@ApiOperation(value="新闻咨询-编辑", notes="新闻咨询-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody News news) {
		newsService.updateById(news);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "新闻咨询-通过id删除")
	@ApiOperation(value="新闻咨询-通过id删除", notes="新闻咨询-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		newsService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "新闻咨询-批量删除")
	@ApiOperation(value="新闻咨询-批量删除", notes="新闻咨询-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.newsService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @return
	 */
	@AutoLog(value = "新闻咨询-通过id查询")
	@ApiOperation(value="新闻咨询-通过id查询", notes="新闻咨询-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="newsId",required=true) String newsId,@RequestParam(name="openId",required=true) String openId) {
		News news = newsService.getById(newsId);
		NewsPraise praise = praiseService.getOneByOpenIdAndCommentId(openId,newsId);
		if(praise !=null){
			news.setIsPraise(1);
			if(news.getAttachment() != null)
			{
				String[] split = news.getAttachment().split(",");
				String strUrl = "";
				for(int j=0;j<split.length;j++)
				{
					String url = split[j];
					strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
				}
				if(strUrl.length()>1)
				{
					strUrl = strUrl.substring(0,strUrl.length() - 1);
				}
				news.setAttachment(strUrl);
			}
			if(news.getImgUrl() !=null){
				String[] split = news.getImgUrl().split(",");
				String strUrl = "";
				for(int j=0;j<split.length;j++)
				{
					String url = split[j];
					strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
				}
				if(strUrl.length()>1)
				{
					strUrl = strUrl.substring(0,strUrl.length() - 1);
				}
				news.setImgUrl(strUrl);
			}
		}
		if(news==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(news);
	}
	 /**
	  *   添加
	  *
	  * @param news
	  * @return
	  */
	 @AutoLog(value = "新闻咨询-评价表-更新阅读次数")
	 @ApiOperation(value="新闻咨询-评价表-更新阅读次数", notes="新闻咨询-评价表-更新阅读次数")
	 @PostMapping(value = "/updateClickCount")
	 public Result<?> updateClickCount(@RequestBody News news) {
		 news = newsService.getById(news.getId());
		 news.setClickCount(news.getClickCount() == null ? 1 : news.getClickCount()+1);
		 newsService.updateById(news);
		 return Result.OK("添加成功！");
	 }
    /**
    * 导出excel
    *
    * @param request
    * @param news
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, News news) {
        return super.exportXls(request, news, News.class, "新闻咨询");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, News.class);
    }
	 /**
	  *  批量审核
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "新闻咨询-批量审核")
	 @ApiOperation(value="新闻咨询-批量审核", notes="新闻咨询-批量审核")
	 @DeleteMapping(value = "/auditBatch")
	 public Result<?> auditBatch(@RequestParam(name="ids",required=true) String ids,@RequestParam(name="auditValue",required=true) int auditValue) {
		 this.newsService.auditBatch(ids,auditValue);
		 String[] newsArr = ids.replace("'","").split(",");
		 String strMsg = "已通过审核";
		 for (int i=0;i<newsArr.length;i++)
		 {
		 	if(auditValue == 2)
			{
				strMsg = "未通过审核";
			}
			 News news = newsService.getById(newsArr[i]);
			 SysUser sysuser = sysUserService.getById(news.getUnionId());
			 if (sysuser != null && !StringUtils.isEmpty(sysuser.getPhone())) {
				 String msg = ChuangLanSmsHelper.PASS_CODE.replace("{$var}", String.format("【%s】%s",news.getTitle(),strMsg ));
				 if (ChuangLanSmsHelper.sendMsg(msg, sysuser.getPhone())) {
					 log.info("新闻咨询-批量审核发送短信成功！消息发送到：" + sysuser.getPhone() + "，内容为【" + msg + "】");
				 } else {
					 log.info("新闻咨询-批量审核发送短信失败！");
				 }
			 }
		 }
		 return Result.OK("批量审核成功!");
	 }

	 /**
	  *  新闻资讯-发布-驳回
	  *
	  * @param id
	  * @param auditDesc
	  * @return
	  */
	 @AutoLog(value = "新闻资讯-发布-驳回")
	 @ApiOperation(value="新闻资讯-发布-驳回", notes="新闻资讯-发布-驳回")
	 @DeleteMapping(value = "/unAudit")
	 public Result<?> unAudit(@RequestParam(name="id",required=true) String id,@RequestParam(name="auditDesc",required=true) String auditDesc) {
		 News entity = newsService.getById(id);
		 if (entity.getStatus() == 0){
			 return Result.error("数据已审核完毕，无法驳回!");
		 }
		 if (entity.getStatus() == 2){
			 return Result.error("数据已驳回!");
		 }

		 entity.setStatus(2);
		 entity.setAuditDesc(auditDesc);
		 newsService.updateById(entity);

		 String strMsg = "未通过审核：" + auditDesc;
		 SysUser sysuser = sysUserService.getById(entity.getUnionId());
		 if (sysuser != null && !StringUtils.isEmpty(sysuser.getPhone())) {
			 String msg = ChuangLanSmsHelper.PASS_CODE.replace("{$var}", String.format("【%s】%s", entity.getTitle(), strMsg));
			 if (ChuangLanSmsHelper.sendMsg(msg, sysuser.getPhone())) {
				 log.info("新闻资讯-发布-驳回，发送短信成功！消息发送到：" + sysuser.getPhone() + "，内容为【" + msg + "】");
			 } else {
				 log.info("新闻资讯-发布-驳回，发送短信失败！");
			 }
		 }
		 return Result.OK("数据驳回成功!");
	 }
}
